﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Mail;

namespace pwblog.Common
{
    public class MailAssistant
    {
        private static string username;
        private static string password;
        public static void SetupSender(string _username, string _password)
        {
            username = _username;
            password = _password;
        }
        public static bool SendMail(string[] clientEmails, string subject, string message, string[] cc)
        {
            if (clientEmails != null)
            {
                try
                {
                    MailMessage mailMessager = new MailMessage();

                    mailMessager.From = new MailAddress(username);

                    foreach (string clientEmail in clientEmails)
                    {
                        if (clientEmail != string.Empty)
                            mailMessager.To.Add(clientEmail);
                    }

                    if (cc != null)
                    {
                        foreach (string c in cc)
                        {
                            if (c != string.Empty)
                                mailMessager.CC.Add(c);
                        }
                    }

                    mailMessager.IsBodyHtml = true;
                    mailMessager.Priority = MailPriority.Normal;
                    mailMessager.SubjectEncoding = System.Text.Encoding.UTF8;
                    mailMessager.Subject = subject;
                    mailMessager.BodyEncoding = System.Text.Encoding.UTF8;
                    mailMessager.Body = message;

                    SmtpClient smtpClient = new SmtpClient();
                    smtpClient.Port = 587;
                    smtpClient.EnableSsl = true;
                    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                    smtpClient.UseDefaultCredentials = false;
                    smtpClient.Credentials = new NetworkCredential(mailMessager.From.ToString(), password);
                    smtpClient.Host = "smtp.gmail.com";

                    smtpClient.Send(mailMessager);
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
            return false;
        }
    }
}